package com.eqxiu.ieditor.api.controller.weixin;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.eqxiu.ieditor.weixin.api.WeiXinServiceApi;


@RestController
public class EventController {

	@Autowired
	private WeiXinServiceApi weiXinServiceApi;

	private Logger logger = LoggerFactory.getLogger(getClass());

	// /?signature=74bc92628b3cfcffc22f1ab1a20cbd9104a8d0a7&echostr=14531509553054088799&timestamp=1499666443&nonce=3073528426
	/**
	 *
	 * @description 接收第一次微信授权验证访问,GET请求
	 * @author ranger
	 * @date Sep 18, 2017
	 * @modified by xxx 修改说明
	 * @param req
	 * @param resp
	 */
	@RequestMapping(value = "/event", method = { RequestMethod.GET })
	public void handleFirst(HttpServletRequest req, HttpServletResponse resp) {

		String echostr = req.getParameter("echostr");
		try {
			resp.getWriter().write(echostr);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 *
	 * @description 接收事件并处理微信通知。<br/>
	 * 有多种微信通知类型，可以在在业务中实现统计、发送消息等操作.
	 * @author ranger
	 * @date Jul 10, 2017
	 * @modified by xxx 修改说明
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/event", method = { RequestMethod.POST })
	public void handleEventNofify(@RequestBody String content, HttpServletResponse resp) throws Exception {
		resp.setCharacterEncoding("utf-8");
		String respTxt = weiXinServiceApi.processNotify(content);
		logger.info("handleEventNofify content = {}",content);
		if (respTxt != null)
			resp.getWriter().write(respTxt);
	}
}
